let header = {
  Accept: "application/json",
  "Content-Type": "application/json"
};

// 处理url
const handleUrl = (url: string) => (params: any) => {
  if (params) {
    let paramsArray: Array<any> = [];
    Object.keys(params).forEach(key =>
      paramsArray.push(key + "=" + encodeURIComponent(params[key]))
    );
    if (url.search(/\?/) === -1) {
      typeof params === "object" ? (url += "?" + paramsArray.join("&")) : url;
    } else {
      url += "&" + paramsArray.join("&");
    }
  }
  return url;
};

// 超时处理
const timeoutFetch = (originalFetch: any, timeout = 5000) => {
  // 定义超时 promise
  let timeoutPromise = new Promise((reject: any) => {
    setTimeout(() => {
      // 请求超时处理
      reject("timeout promise");
    }, timeout);
  });
  // Promise.race(iterable)方法返回一个promise, 哪个获得快 就返回哪个 promise
  let abortPromise = Promise.race([originalFetch, timeoutPromise]);
  return abortPromise;
};

export default class Network {
  static getRequest: any = (url: string, params: any = {}) => {
    return timeoutFetch(
      fetch(handleUrl(url)(params), {
        method: "GET",
        headers: header
      })
    )
      .then((response: any) => {
        if (response.ok) {
          return response.json();
        } else {
          // 解析失败
          console.warn(`解析json失败:${response}`);
        }
      })
      .then((responseJson: any) => {
        // 业务处理 code msg data
        if (responseJson && responseJson.code === 1) {
          return responseJson;
        } else {
          // 非正确的code值，错误处理
          console.warn(`逻辑错误: ${responseJson}`);
        }
      })
      .catch((error: Error) => {
        console.warn(error);
      });
  };

  static postRequest: any = (url: string, params: any = {}) => {
    let formData = new FormData();
    Object.keys(params).forEach(key => {
      formData.append(key, params[key]);
    });
    return timeoutFetch(
      fetch(url, {
        method: "POST",
        headers: header,
        body: formData
      })
    )
      .then((response: any) => {
        if (response.ok) {
          return response.json();
        } else {
          // 解析失败
          console.warn(`解析json失败:${response}`);
        }
      })
      .then((responseJson: any) => {
        if (responseJson && responseJson.code === 1) {
          return responseJson;
        } else {
          // 非正确的code值，错误处理
          console.warn(`逻辑错误: ${responseJson}`);
        }
      })
      .catch((error: Error) => {
        console.warn(error);
      });
  };
}
